let validateResult = []; // 存储执行结果

document.addEventListener('DOMContentLoaded', () => {
    chrome.storage.local.get(['validateResult'], (result) => {
        if (chrome.runtime.lastError) {
            console.error('Error reading from chrome.storage.local', chrome.runtime.lastError);
        } else {
            validateResult = result.validateResult;
            renderResult();
        }
    });
});

// 从storeage中读取配置
async function readFromStorageAsync() {
    return new Promise((resolve, reject) => {
        chrome.storage.local.get(['rules'], (result) => {
            if (chrome.runtime.lastError) {
                console.error('Error reading from chrome.storage.local', chrome.runtime.lastError);
                reject(chrome.runtime.lastError);
            } else {
                resolve(result.rules);
            }
        });
    });
}

// 高亮
function onHighlight(e) {
    const { path, type, index } = e.target.dataset;
    console.log(path, type, index);
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        const currentTab = tabs[0];
        chrome.scripting.executeScript(
            {
                target: { tabId: currentTab.id },
                func: (path, type, index) => {
                    if (typeof uiaActions !== 'undefined') {
                        return uiaActions?.highlight(path, type, index);
                    }
                },
                args: [path, type, index],
            },
            (results) => {
                console.log(results);
            },
        );
    });
}

// 开始
async function onStart() {
    const rules = await readFromStorageAsync();

    // 获取当前 tab 页面
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        const currentTab = tabs[0];

        // 在当前页面执行脚本，获取所有 button 元素
        chrome.scripting.executeScript(
            {
                target: { tabId: currentTab.id },
                func: (rules) => {
                    if (typeof uiaActions !== 'undefined') {
                        return uiaActions?.validate(rules);
                    }
                },
                args: [rules],
            },
            (results) => {
                // 获取并显示脚本执行结果
                validateResult = results?.[0]?.result;
                chrome.storage.local.set({ validateResult }, () => {
                    if (chrome.runtime.lastError) {
                        document.getElementById('statusMessage').textContent = 'Error saving data.';
                    } else {
                        // 保存成功后执行
                        renderResult();
                    }
                });
            },
        );
    });
}

function renderResult() {
    try {
        let str = `
        <ul id="list" class="popup-list">`;
        for (const item of validateResult) {
            const { validator, description, data } = item;

            for (const dataItem of data) {
                const { attribute, data, message } = dataItem;
                str += `
                    <li class="popup-item"> 
                        <div class="popup-box">
                            <span class="popup-label">验证描述:</span>
                            <span class="popup-value">${description}</span>
                        </div>
                        <div class="popup-box">
                            <span class="popup-label">验证属性:</span>
                            <span class="popup-value">${attribute}</span>
                        </div>
                        <div class="popup-box">
                            <span class="popup-label">验证结果:</span>
                            <span class="popup-value">${message}</span>
                        </div>
                        <div class="popup-box">
                            <span class="popup-label">失败列表:</span>
                            <ul class="popup-list">`;

                if (validator === 'exist-validator') {
                    let eleIndex = 0;
                    for (const datItem of data) {
                        const { paths } = datItem;
                        str += `
                                <li class="popup-item">
                                    <div class="popup-box">
                                        <span class="popup-label">元素${(eleIndex += 1)}:</span>
                                        <ul class="popup-list">
                                        `;

                        for (const pathItem of paths) {
                            const { path, index, description, type } = pathItem;
                            str += ` 
                                            <li class="popup-item">
                                                <div>path:${path}</div>
                                                <div>type:${type}</div>
                                                <div>index:${index}</div>
                                                <div>description:${description}</div>
                                            </li>
                                            `;
                        }

                        str += `
                                        </ul>
                                    </div>
                                    <button 
                                    class="popup-button" 
                                    data-path="${paths[0].path}"
                                    data-type="${paths[0].type}"
                                    data-index="${paths[0].index}"
                                    >高亮</button>
                                </li>`;
                    }
                } else if (validator === 'unique-validator') {
                    for (const dataItem of data) {
                        const { value, count } = dataItem;
                        const dataPath = {
                            path: `[${attribute}='${value}']`,
                            index: -1,
                            type: 'selector',
                        };
                        JSON.stringify(dataPath);
                        str += `
                        <li class="popup-item">
                            <div class="popup-box">
                                <span class="popup-label">元素属性:</span>
                                <span class="popup-value">${attribute}=${value}</span>
                                
                            </div>
                            <div class="popup-box">
                                <span class="popup-label">元素个数:</span>
                                <span class="popup-value">${count}</span>
                            </div>
                            <button 
                                class="popup-button" 
                                data-path="${dataPath.path}"
                                data-type="${dataPath.type}"
                                data-index="${dataPath.index}" 
                            >
                                    高亮
                            </button>
                    </li>`;
                    }
                }
                str += '</ul>';
            }
        }
        str += `
        </ul>`;
        document.getElementById('result').innerHTML = str;
        const btns = document.getElementById('result').querySelectorAll('.popup-button');
        btns.forEach((btn) => {
            btn.addEventListener('click', onHighlight);
        });
        // document.getElementById('json').textContent = '检测结果:\n' + JSON.stringify(validateResult, null, 2);
    } catch (error) {}
}

// 上报结果
function reportResult() {
    if (window.isDownload) {
        if (validateResult.length === 0) {
            alert('No data available to export.');
            return;
        }

        // 创建一个 Blob 对象来存储 JSON 数据
        const jsonBlob = new Blob([JSON.stringify(validateResult, null, 2)], { type: 'application/json' });

        // 创建下载链接
        const url = URL.createObjectURL(jsonBlob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `result-${new Date().toLocaleDateString()}.json`; // 设置下载文件的默认名称
        a.click();

        // 释放 Blob URL
        URL.revokeObjectURL(url);
    }
}

// 获取 Start 按钮并为其添加点击事件
document.getElementById('startButton').addEventListener('click', onStart);

// 导出数据为 JSON 文件
document.getElementById('reportResult').addEventListener('click', reportResult);
